/* @Author      guang
 * @description 登录拦截放行时，设置虚拟角色
 */
import { defineStore } from 'pinia';
// import { postLogin, postLogout, postUserInfo } from '@/api/userCenter';
import { postAuthLogin, postAuthLogout, postUserInfo } from '@/api/common';
// import { postFeedbackNoReadNum } from "@/api/common";
import router from '@/router';
// 仓库数据
import { useStorePermission } from '@/store';
export const useStoreUser = defineStore('user', {
  state: () => {
    return {
      token: '',
      feedBackNum: 0,
      userInfo: {
        typeList: [],
        roles: [],
      },
      rsaKey: '',
      activateUser: '',
      searchHistory: [],
    };
  },
  actions: {
    async userLogin(params) {
      // 调取登录接口，存储登录信息
      const response = await postAuthLogin(params);
      const accessToken = response?.data?.token;
      const activateUserInfo = response?.data?.activateUser;
      this.activateUser = activateUserInfo;
      this.userInfo = response?.data || null;
      // this.getUserInfo();
      if (accessToken) {
        this.token = accessToken;
        return Promise.resolve(true);
      }
      return Promise.reject(false);
    },
    getUserInfo() {
      // 获取用户信息
      return postUserInfo().then(result => {
        this.userInfo = result.data || null;
      });
    },
    setUserInfo(params) {
      this.userInfo = Object.assign(this.userInfo, params || {});
    },
    logout() {
      const storePermission = useStorePermission();
      return new Promise(resolve => {
        postAuthLogout()
          .then(() => {
            storePermission.changeValue('prower', {});
            storePermission.changeValue('addRouters', []);
            storePermission.changeValue('menuList', []);
            this.token = '';
            router.push('/login');
            resolve();
          })
          .catch(() => {
            // resolve()
          });
      });
    },
    // 添加新搜索记录
    addSearchHistory(value) {
      if (value === '') {
        return;
      }
      let index = this.searchHistory.findIndex(t => t === value);
      // 如果存在，则需要先删除，再添加
      if (index > -1) {
        this.searchHistory.splice(index, 1);
      }
      this.searchHistory.unshift(value);
    },

    // 获取意见反馈未读数量
    async getFeedBackNum() {
      // const res = await postFeedbackNoReadNum();
      // console.log(res);
      this.feedBackNum = res.data.num;
    }
  },
  persist: {
    key: 'store-user',
    storage: window.localStorage,
    paths: ['userInfo', 'token', 'rsaKey', 'activateUser', 'searchHistory'],
  },
});
